package crp.services.api.graphql.loaders;

import com.qwlabs.lang.C2;
import crp.core.workflow.app.WorkflowService;
import crp.core.workflow.domain.models.WorkflowInstanceEntity;
import crp.services.api.graphql.models.WorkflowInstancePayload;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.*;
import java.util.function.Function;

@ApplicationScoped
public class WorkflowInstanceFetcher {
    private final WorkflowService workflowService;

    @Inject
    public WorkflowInstanceFetcher(WorkflowService workflowService) {
        this.workflowService = workflowService;
    }

    public List<WorkflowInstancePayload> fetch(Collection<String> ids) {
        Map<String, WorkflowInstancePayload> mapping = C2.map(workflowService.instanceSearcher().byIds(ids),
                WorkflowInstanceEntity::getId,
                WorkflowInstancePayload::of);
        return C2.list(ids, mapping::get);
    }

    public <S> List<WorkflowInstancePayload> fetch(List<S> sources, Function<S, String> idMapper) {
        Set<String> ids = C2.set(sources, idMapper, Objects::nonNull);
        Map<String, WorkflowInstancePayload> mapping = C2.map(workflowService.instanceSearcher().byIds(ids),
                WorkflowInstanceEntity::getId,
                WorkflowInstancePayload::of);
        return C2.list(sources, source ->
                Optional.ofNullable(idMapper.apply(source))
                        .map(mapping::get)
                        .orElse(null));
    }
}
